import { create } from "zustand";
import type {
  LoginApiParams,
  LoginApiResponse,
  GetUserInfoApiResponse,
} from "../lib/api/system.d";
import { loginApi, getUserInfoApi } from "../lib/api/system";
import { setToken } from "@/lib/utils/auth";
import type { User } from "../lib/api/system/user.d";

type UserStore = {
  token: string; // 令牌
  tenantId: string; // 租户ID
  clientId: string; // 客户端ID
  user: User | null; // 用户信息
  roles: string[]; // 角色
  permissions: string[]; // 权限
  login: (data: any) => Promise<LoginApiResponse>;
  getUserInfo: () => Promise<GetUserInfoApiResponse>;
};

export const useUserStore = create<UserStore>((set) => ({
  token: "", // 令牌
  name: "", // 名称
  nickname: "", // 昵称
  userId: "", // 用户ID
  tenantId: "", // 租户ID
  avatar: "", // 头像
  clientId: "", // 客户端ID
  user: null, // 用户信息
  roles: [], // 角色
  permissions: [], // 权限
  login: async (params: LoginApiParams) => {
    const { data } = await loginApi(params);
    set({
      token: data.access_token,
      clientId: data.clientId,
      tenantId: params.tenantId,
    });
    setToken(data.access_token);
    return data;
  },
  getUserInfo: async () => {
    const { data } = await getUserInfoApi();

    set({
      roles: data.roles,
      permissions: data.permissions,
      user: data.user,
    });

    return data;
  },
}));
